package com.github.hgkmail.hello.leetcode101.firstsearch;

import java.util.*;

public class LC46Permutations {
    //回溯法，深度优先的特殊情况，遍历过程要记录操作信息和还原修改。
    public void backtrack(int[] nums, Set<Integer> used, List<Integer> aCase, List<List<Integer>> res) {
        //位数达到上限，返回
        if (aCase.size()>=nums.length) {
            res.add(new ArrayList<>(aCase)); //这里要用拷贝
            return;
        }
        //尝试加数字
        for (int j = 0; j < nums.length; j++) {
            Integer n = nums[j];
            if (used.contains(n)) { //用过的数字，跳过
                continue;
            }
            //加一位
            aCase.add(n);
            used.add(n);
            backtrack(nums, used, aCase, res);
            //还原
            aCase.remove(n);
            used.remove(n);
        }
    }

    public List<List<Integer>> permute(int[] nums) {
        if (nums.length<=0) {
            return new ArrayList<>();
        }
        Set<Integer> used = new HashSet<>(nums.length);
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> aCase = new ArrayList<>();
        backtrack(nums, used, aCase, res);

        return res;
    }

    public static void main(String[] args) {
        System.out.println(new LC46Permutations().permute(new int[]{1,2,3}));
    }
}
